﻿/*
 * @Author: Dreamy Icecream 
 * @Date: 2020-12-31 14:53:32 
 * @Description: Bloom效果
 * @Last Modified by: Dreamy Icecream
 * @Last Modified time: 2020-12-31 16:17:01
 */
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Bloom : PostEffectsBase {

    public Shader bloomShader;

    private Material bloomMaterial = null;
    public Material material {
        get {
            this.bloomMaterial = CheckShaderAndCreateMaterial (this.bloomShader, this.bloomMaterial);
            return this.bloomMaterial;
        }
    }

    /** 迭代次数 */
    [Range (0, 4)]
    public int iterations = 3;

    /** 范围 */
    [Range (0.2f, 3.0f)]
    public float blurSpread = 0.6f;

    /** 缩放系数 */
    [Range (1, 8)]
    public int downSample = 2;

    /** 光亮阈值 */
    [Range (0.0f, 4.0f)]
    public float luminanceThreshold = 0.6f;

    private void OnRenderImage (RenderTexture src, RenderTexture dest) {
        if (this.material != null) {
            this.material.SetFloat ("_LuminanceThreshold", this.luminanceThreshold);

            int rtW = src.width / this.downSample;
            int rtH = src.height / this.downSample;

            RenderTexture buffer0 = RenderTexture.GetTemporary (rtW, rtH, 0);
            buffer0.filterMode = FilterMode.Bilinear;

            Graphics.Blit (src, buffer0, this.material, 0);

            for (int index = 0; index < this.iterations; index++) {
                this.material.SetFloat ("_BlurSize", 1.0f + index * this.blurSpread);

                RenderTexture buffer1 = RenderTexture.GetTemporary (rtW, rtH, 0);
                Graphics.Blit (buffer0, buffer1, this.material, 1);
                RenderTexture.ReleaseTemporary (buffer0);
                buffer0 = buffer1;

                buffer1 = RenderTexture.GetTemporary (rtW, rtH, 0);
                Graphics.Blit (buffer0, buffer1, this.material, 2);
                RenderTexture.ReleaseTemporary (buffer0);
                buffer0 = buffer1;
            }

            this.material.SetTexture ("_Bloom", buffer0);
            Graphics.Blit (src, dest, material, 3);

            RenderTexture.ReleaseTemporary (buffer0);

        } else {
            Graphics.Blit (src, dest);
        }
    }

}